package com.automobile.controller;

import com.alibaba.fastjson.JSON;
import com.automobile.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 异常处理类
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-05-10 16:23
 */
@Slf4j
@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    public void  exceptionHandler(HttpServletRequest request,
                                  HttpServletResponse response, Exception e) throws Exception {

        log.error(e.getMessage(), e);
        if (isAjax(request)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            //具体操作
            writer.write(JSON.toJSONString(Result.errorOf(HttpStatus.NOT_FOUND.value(), e.getMessage())));
            //
            writer.flush();
            writer.close();

            //return Result.errorOf(HttpStatus.NOT_FOUND.value(), e.getMessage());
        } else {
//            ModelAndView mav = new ModelAndView();
//            mav.addObject("exception", e.getMessage());
//            mav.addObject("url", request.getRequestURL());
//            mav.setViewName("error/error");
//            return mav;
            throw e;
        }

    }

    /**
     * 判断是否是ajax请求
     */
    public static boolean isAjax(HttpServletRequest httpRequest) {
        return (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals(httpRequest.getHeader("X-Requested-With").toString()));
    }


}
